<template>
  <!--上传图片-->
  <a-spin :spinning="spinning" tip="加载中。。。">
  <span style="position: relative;">
    <input type="file" id="file" accept="image/*" @change="upImg">
    <!--<audio id="audio_id" controls loop></audio>-->
    <a-button class="btnUp" @click="toUp" v-if="msg==''||msg==null"><a-icon type="upload"/>上传图片</a-button>
    <a-button class="btnUp" @click="toUp" v-else><a-icon type="upload"/>{{msg}}</a-button>
  </span>
  </a-spin>
</template>
<script>
  import {uploadVideo,livedelFile} from '@/api/courseManage/live'
  export default {
    inject: ['upShow'],
    props: {
      /*   -------弹窗--------*/
      id: [String],
      msg: [String],
    },
    data() {
      return {
        spinning: false
      }
    },
    created() {

    },
    methods: {
      toUp() {
        if(this.id != '' && this.id != null) {
          var that = this
          this.$confirm({
            title: '上传新的图片需要删除旧的图片',
            content: '确定删除'+this.msg +'?',
            onOk() {
              that.delImg()
            },
            onCancel() {},
          });
        }else {
          document.getElementById('file').click();
        }
      },
      delImg() {
        this.spinning = true
        livedelFile(this.id).then(res => {
          this.spinning = false
          if(res.code == 200) {
            this.upShow(1,"旧图片删除成功")
            this.$emit('update:msg','')
            this.$emit('getImgFile','')
            document.getElementById('file').click();
          }else {
            this.upShow(2,res.msg)
          }
        }).catch(err => {
          this.spinning = false
          this.upShow(2)
        })
      },
      upImg() {
        this.spinning = true
        var file = document.getElementById('file').files[0];
        var url = URL.createObjectURL(file);
        console.log('url:'+url);
        let formData = new FormData();
        formData.append("file", file);
        uploadVideo(formData).then(res => {
          this.spinning = false
          if(res.code == 200) {
            this.upShow(1,"图片上传成功")
            this.$emit('update:msg',res.data.fileName)
            this.$emit('update:id',res.data.fileNo)
            this.$emit('getImgFile',res.data)
          } else {
            this.upShow(2,res.msg)
          }
        }).catch(err => {
          this.spinning = false
          this.upShow(2)
        })
      }
    }
  }
</script>
<style scoped="" lang="less">
  input {
    opacity: 0;
    width: 160px;
    height: 33px;
  }
  .btnUp {
    position: absolute;
    left: 0;
    top: 2px;
    width: 160px;
    height: 33px;
    font-size: 15px;
    span {
      display: inline-block;
      width: 100px;
      overflow: hidden;
      text-overflow:ellipsis;
      white-space: nowrap;
      vertical-align: middle;
    }
  }
</style>